#import "MainTableViewController.h"
#import "WebviewViewController.h"
#import "TableViewCell.h"
#define GAP 20
#define SEARCH_W (width - GAP - 170)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

@interface MainTableViewController ()
{
    NSArray *alphabet;
    NSArray *sortDrug;
    NSArray *sortDrugSearch;
    NSMutableDictionary *dataDrugs;
    NSMutableDictionary *dataDrugsSearch;
    BOOL isIos7;
    BOOL isSearch;
    int lengthSearch;
}
@end

@implementation MainTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) viewWillAppear:(BOOL)animated{
    [self setTitle:@"Drugs Dictionary Pro"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //create search
    _searchItem = [self resourceBasedButton:@"ic_magnifying_glass" withAction:@selector(onShowSearch:)];
    _backButton = [self resourceBasedButton:@"ic_arrow_left" withAction:@selector(onCancel:)];
    [[self navigationItem] setRightBarButtonItem:_searchItem];
    _searchBar = [[UISearchBar alloc] initWithFrame: CGRectMake(0,0,50,32)];
    [_searchBar setPlaceholder: @"Search"];
	[_searchBar setDelegate: self];
    dataDrugsSearch = [[NSMutableDictionary alloc] init];
    
    isIos7 = SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0");
    alphabet = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
    
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                        initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(160, 240);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];
    [[self tableView] setHidden:YES];
    //Start an activity indicator here
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        //Call your function or whatever work that needs to be done
        //Code in this part is run on a background thread
        dataDrugs = [self getAllData];
        sortDrug = [[dataDrugs allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
        
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            
            //Stop your activity indicator or anything else with the GUI
            //Code here is run on the main thread
            [[self tableView] reloadData];
            [spinner setHidden:YES];
            [spinner stopAnimating];
            [[self tableView]setHidden:NO];
        });
    });
   
    
    if (isIos7) {
        self.tableView.sectionIndexBackgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    } else {
        [self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:0 green:153.0/255 blue:253.0/255 alpha:0]];
        NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                                   [UIColor whiteColor],UITextAttributeTextColor,
                                                   [UIColor whiteColor], UITextAttributeTextShadowColor,
                                                   [NSValue valueWithUIOffset:UIOffsetMake(0, 0)], UITextAttributeTextShadowOffset, nil];
        [self.navigationController.navigationBar setTitleTextAttributes:navbarTitleTextAttributes];
        [_searchBar setTranslucent:YES];
        for (UIView *subview in _searchBar.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
            {
                [subview removeFromSuperview];
                break;
            }
        }
        [_searchBar setTintColor:[UIColor colorWithRed:0 green:153.0/255 blue:253.0/255 alpha:0]];
    }
    
    self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_bg"]];
    self.tableView.backgroundColor = [UIColor clearColor];
    //Add padding to the top of the table view
    self.tableView.sectionIndexColor = [UIColor whiteColor];
}

-(void) viewDidLayoutSubviews{
    CGSize size = [[self tableView] frame].size;
    width = size.width;
    [_searchBar setFrame: CGRectMake(0,0,SEARCH_W,32)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (isSearch) {
        return sortDrugSearch.count;
    }else {
        return sortDrug.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (isSearch) {
        NSString *sectionTitle = [sortDrugSearch objectAtIndex:section];
        NSArray *sectionDrugs = [dataDrugsSearch objectForKey:sectionTitle];
        return [sectionDrugs count];
    }else{
        NSString *sectionTitle = [sortDrug objectAtIndex:section];
        NSArray *sectionDrugs = [dataDrugs objectForKey:sectionTitle];
        return [sectionDrugs count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (isSearch && lengthSearch > 1 && lengthSearch != 0) {
        return 0.01;
    }else{
        return 20;
    }
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    [view setTintColor:[UIColor colorWithRed:50.0/255 green:180.0/255 blue:229.0/255 alpha:1]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!isIos7) {
        for(UIView *view in [self.tableView subviews])
        {
            if([[[view class] description] isEqualToString:@"UITableViewIndex"])
            {
                [view setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.4]];
            }
        }
    }
    static NSString *identifier = @"MainCell";
    TableViewCell *cell = (TableViewCell *)[tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (isSearch) {
        NSString *sectionTitle = [sortDrugSearch objectAtIndex:indexPath.section];
        NSArray *sectionDrugs = [dataDrugsSearch objectForKey:sectionTitle];
        if ([sectionDrugs count]>0) {
            DrugItem *drug = [sectionDrugs objectAtIndex:indexPath.row];
            cell.avatar.image = [UIImage imageNamed:[drug image]];
            cell.title.text = [drug name];
            cell.description.text = [drug desShort];
            cell.idDrugs = [drug idDrug];
        }
    }else{
        NSString *sectionTitle = [sortDrug objectAtIndex:indexPath.section];
        NSArray *sectionDrugs = [dataDrugs objectForKey:sectionTitle];
        DrugItem *drug = [sectionDrugs objectAtIndex:indexPath.row];
        cell.avatar.image = [UIImage imageNamed:[drug image]];
        cell.title.text = [drug name];
        cell.description.text = [drug desShort];
        cell.idDrugs = [drug idDrug];

    }
    return cell;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return alphabet;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (isSearch && lengthSearch > 1 && lengthSearch != 0) {
        return @"";
    }else{
        return [sortDrug objectAtIndex:section];
    }
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (isSearch) {
        return [sortDrugSearch indexOfObject:title];
    }else{
        return [sortDrug indexOfObject:title];
    }
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    WebviewViewController * vc = [segue destinationViewController];
    vc.idDrugs = [sender idDrugs];
}

-(NSMutableDictionary *) getAllData{
    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsPath = [paths objectAtIndex:0];
    NSString *dbPath = [docsPath stringByAppendingPathComponent:@"drugs.db"];
    NSMutableDictionary *dicData = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < alphabet.count; i++) {
        NSString *key = [alphabet[i] copy];
        NSMutableArray *data = [[NSMutableArray alloc] init];
        [dicData setValue:data forKey:key];
    }
    
    FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
    [database open];
    NSString *sqlSelectQuery = @"SELECT * FROM drugs";
    FMResultSet *resultsWithNameLocation = [database executeQuery:sqlSelectQuery];
    while([resultsWithNameLocation next]) {
        int idDrug = [resultsWithNameLocation intForColumn:@"id"];
        NSString *strName = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"name"]];
        NSString *strImage =  [[NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"image"]] stringByAppendingString:@".png"];
        NSString *strDesShort = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"desshort"]];
        NSString *key = [[strName substringToIndex:1] uppercaseString];
        DrugItem *item = [[DrugItem alloc]initWithShortInfo:idDrug withNameDrug:strName withImageName:strImage withShortDes:strDesShort];
        [[dicData valueForKey:key] addObject:item];
    }
    [database close];
    return dicData;
}
- (UIBarButtonItem *) resourceBasedButton:(NSString *)resource withAction:(SEL)selector
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
	{
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:resource] forState:0];
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        if([@"ic_arrow_left" isEqualToString:resource])
        {
            btn.frame = CGRectMake(0, 0, 32, 32);
        }
        else if([@"ic_magnifying_glass" isEqualToString:resource])
        {
            btn.frame = CGRectMake(0, 0, 22, 22);
        }        else{
            btn.frame = CGRectMake(0, 0, 24, 24);
        }
        [btn setContentMode:UIViewContentModeScaleAspectFill];
        UIBarButtonItem *ib = [[UIBarButtonItem alloc] initWithCustomView:btn];
        return ib;
        
	}
	else
	{
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:resource] forState:0];
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        if([@"ic_arrow_left" isEqualToString:resource])
        {
            btn.frame = CGRectMake(0, 0, 32, 32);
        }
        else if([@"ic_magnifying_glass" isEqualToString:resource])
        {
            btn.frame = CGRectMake(0, 0, 22, 22);
        }
        else{
            btn.frame = CGRectMake(0, 0, 24, 24);
        }
        [btn setContentMode:UIViewContentModeScaleAspectFill];
        UIBarButtonItem *ib = [[UIBarButtonItem alloc] initWithCustomView:btn];
        return ib;
	}
}

- (void) onShowSearch: (id)sender
{
    [[self navigationItem] setLeftBarButtonItem:_backButton];
    [[self navigationItem] setRightBarButtonItem:nil];
    [[self navigationItem] setTitleView: _searchBar];
    isSearch = YES;
	[_searchBar becomeFirstResponder];
    if([[_searchBar text] length] >0)
    {
        lengthSearch = [[_searchBar text] length];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dataDrugsSearch = [[NSMutableDictionary alloc] init];
            BOOL result = NO;
            for (int i = 0; i < alphabet.count; i++) {
                NSString *key = [alphabet[i] copy];
                NSMutableArray *data = [[NSMutableArray alloc] init];
                NSMutableArray *dataTemp = [dataDrugs valueForKey:key];
                for (int i = 0; i < [dataTemp count]; i++) {
                    DrugItem *item = [dataTemp objectAtIndex:i];
                    if ([[item name] rangeOfString:[_searchBar text]].location != NSNotFound) {
                        [data addObject:item];
                        result = YES;
                    }
                }
                [dataDrugsSearch setValue:data forKey:key];
            }
            sortDrugSearch = [[dataDrugsSearch allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                if (!result) {
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle: @"No matches found for:"
                                          message: [_searchBar text]
                                          delegate: nil
                                          cancelButtonTitle: @"Close"
                                          otherButtonTitles: nil];
                    [alert show];
                    [[self tableView] reloadData];
                }else{
                    [[self tableView] reloadData];
                }
            });
        });
    }
}
- (void) onCancel: (id)sender
{
    isSearch = NO;
    [[self tableView] reloadData];
    [_searchBar resignFirstResponder];
    [[self navigationItem] setTitleView: nil];
    [[self navigationItem] setLeftBarButtonItem:nil];
    [self setTitle:@"Drugs Dictionary Pro"];
    if(_searchItem)
         [[self navigationItem] setRightBarButtonItem:_searchItem];
    //[self resetSearch];
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if ([[searchBar text] length] > 0) {
        lengthSearch = [[searchBar text] length];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dataDrugsSearch = [[NSMutableDictionary alloc] init];
            BOOL result = NO;
            for (int i = 0; i < alphabet.count; i++) {
                NSString *key = [alphabet[i] copy];
                NSMutableArray *data = [[NSMutableArray alloc] init];
                NSMutableArray *dataTemp = [dataDrugs valueForKey:key];
                for (int i = 0; i < [dataTemp count]; i++) {
                    DrugItem *item = [dataTemp objectAtIndex:i];
                    if ([[item name] rangeOfString:[searchBar text]].location != NSNotFound) {
                        [data addObject:item];
                        result = YES;
                    }
                }
                [dataDrugsSearch setValue:data forKey:key];
            }
            sortDrugSearch = [[dataDrugsSearch allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
            dispatch_async(dispatch_get_main_queue(), ^(void) {
                if (!result) {
                    UIAlertView *alert = [[UIAlertView alloc]
                                          initWithTitle: @"No matches found for:"
                                          message: [searchBar text]
                                          delegate: nil
                                          cancelButtonTitle: @"Close"
                                          otherButtonTitles: nil];
                    [alert show];
                    [[self tableView] reloadData];
                }else{
                    [searchBar resignFirstResponder];
                    [[self tableView] reloadData];
                }
            });
        });
	}else{
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle: @"You must enter search have length > 1"
                              message: nil
                              delegate: nil
                              cancelButtonTitle: @"Close"
                              otherButtonTitles: nil];
        [alert show];
    }
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
}
@end
